package com.yshkj.payment.service.impl.operator;

import com.yshkj.payment.BeanProvider;
import com.yshkj.payment.dto.CommonJsonDto;
import com.yshkj.payment.dto.SpecSaleDto;
import com.yshkj.payment.entity.medicinal.SaleRecord;
import com.yshkj.payment.entity.medicinal.SaleRecordItem;
import com.yshkj.payment.entity.medicinal.Spec;
import com.yshkj.payment.repository.SaleRecordItemRepository;
import com.yshkj.payment.repository.SaleRecordRepository;
import com.yshkj.payment.repository.SpecRepository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 唐旭 on 2016/10/6.
 */
public class SpecListSaleHandler {
    private List<SpecSaleDto> list;

    private transient SpecRepository specRepository = BeanProvider.getBean(SpecRepository.class);
    private transient SaleRecordRepository saleRecordRepository = BeanProvider.getBean(SaleRecordRepository.class);
    private transient SaleRecordItemRepository saleRecordItemRepository = BeanProvider.getBean(SaleRecordItemRepository.class);

    public SpecListSaleHandler(List<SpecSaleDto> list) {
        this.list = list;
    }

    public CommonJsonDto sale() {
        SaleRecord record = new SaleRecord();
        List<Spec> specs = new ArrayList<>();
        for (SpecSaleDto saleDto : list) {
            createRecordItem(saleDto, record);
            reduceSpecCount(saleDto, specs);
        }

        saleRecordRepository.save(record);
        specRepository.save(specs);
        return new CommonJsonDto(true);
    }

    private void reduceSpecCount(SpecSaleDto saleDto, List<Spec> specs) {
        Spec one = specRepository.findOne(saleDto.getUuid());
        one.setCount(one.getCount() - saleDto.getSaleCount());
        specs.add(one);
    }

    private void createRecordItem(SpecSaleDto saleDto, SaleRecord record) {
        SaleRecordItem item = new SaleRecordItem();
        item.setSaleRecord(record);
        saleDto.update(item);
        item.setSpec(specRepository.findOne(saleDto.getUuid()));
        record.getItemList().add(item);
    }
}
